package com.powernode.driver.service.impl;

import com.powernode.driver.config.TencentProperties;
import com.powernode.driver.service.CosService;
import com.powernode.driver.service.OcrService;
import com.powernode.model.vo.driver.CosUploadVo;
import com.powernode.model.vo.driver.IdCardOcrVo;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.joda.time.format.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class OcrServiceImpl implements OcrService {
    @Resource
    private TencentProperties tencentProperties;
    @Resource
    private CosService cosService;

    /**
     * 识别身份证图片信息
     */
    @Override
    public IdCardOcrVo idCardOcr(MultipartFile multipartFile) {
        // 将图片二进制数据转成base64文本
        try {
            byte[] encoded = Base64.encodeBase64(multipartFile.getBytes());
            IDCardOCRResponse response = getIdCardOCRResponse(encoded);
            IdCardOcrVo idCardOcrVo = new IdCardOcrVo();
            // 判断正反面
            if (StringUtils.hasText(response.getName())) {
                // 正面
                idCardOcrVo.setName(response.getName());
                idCardOcrVo.setGender("男".equals(response.getSex()) ? "1" : "2");
                Date birthday = DateTimeFormat.forPattern("yyyy/MM/dd").parseDateTime(response.getBirth()).toDate();
                idCardOcrVo.setBirthday(birthday);
                idCardOcrVo.setIdcardNo(response.getIdNum());
                idCardOcrVo.setIdcardAddress(response.getAddress());
                // 将身份证上传到cos中
                CosUploadVo cosUploadVo = cosService.upload(multipartFile, "idCard");
                idCardOcrVo.setIdcardFrontUrl(cosUploadVo.getUrl());
                idCardOcrVo.setIdcardFrontShowUrl(cosUploadVo.getShowUrl());
            } else {
                // 获取过期时间
                String idCardExpire = response.getValidDate().split("-")[1];
                Date cardExpireDate = DateTimeFormat.forPattern("yyyy.MM.dd").parseDateTime(idCardExpire).toDate();
                idCardOcrVo.setIdcardExpire(cardExpireDate);
                // 反面存储到cos中
                CosUploadVo cosUploadVo = cosService.upload(multipartFile, "idCard");
                idCardOcrVo.setIdcardBackUrl(cosUploadVo.getUrl());
                idCardOcrVo.setIdcardBackShowUrl(cosUploadVo.getShowUrl());
            }
            return idCardOcrVo;
        } catch (IOException | TencentCloudSDKException e) {
            throw new RuntimeException(e);
        }
    }

    private IDCardOCRResponse getIdCardOCRResponse(byte[] encoded) throws TencentCloudSDKException {
        String idCardBase64 = new String(encoded);
        // 创建凭证
        Credential credential = new Credential(tencentProperties.getSecretId(), tencentProperties.getSecretKey());
        // 创建ocrClient
        OcrClient ocrClient = new OcrClient(credential, tencentProperties.getRegion());
        // 创建ocr请求对象
        IDCardOCRRequest request = new IDCardOCRRequest();
        request.setImageBase64(idCardBase64);
        // 发送请求获得结果
        return ocrClient.IDCardOCR(request);
    }
}